package com.shujia.maven.jdbc;

import java.sql.*;

public class Demo1MysqlJdbc {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //1.加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2.建立连接
        /**
         * jdbc url ===> jdbc:mysql://master:3306/db1?useSSl=false
         */
        Connection conn = DriverManager.getConnection("jdbc:mysql://master:3306/db2?useSSl=false", "root", "123456");
        //3.创建statement
        Statement st = conn.createStatement();
       // st.executeQuery();//执行DQl
       // st.execute();//执行DDL,DCL
        // st.executeUpdate();//执行DML
        //查询 年龄 =23 的学生
        //如果用户输入"22 or 1=1 ",那么就会造成数据泄露的问题
        //使用statement容易出现sql注入问题
        System.out.println(args[0]);
        String age=args[0];
        //ResultSet rs = st.executeQuery("select * from student where age =" + age);
        //使用prepareStatement避免注入问题
        PreparedStatement preSt = conn.prepareStatement("select * from student where age =?");
        /**
         * 参数的顺序 从 1开始数
         */
        preSt.setInt(1,Integer.parseInt(age));
        ResultSet rs=preSt.executeQuery();
        //4.如果有数据返回则可以遍历ResultSet
        while (rs.next()){
            int id = rs.getInt("id");
            String name = rs.getString("name");
            int stu_age = rs.getInt("age");
            String gender = rs.getString("gender");
            String clazz = rs.getString("clazz");
            System.out.println(id+","+name+","+age+","+gender+","+clazz);
        }
        //关闭连接
        conn.close();
    }
}
